package com.basin.common.glc.func;

import com.basin.common.glc.context.BasinLogContext;
import com.basin.common.glc.pojo.BasinLogVO;
import feign.InvocationContext;
import feign.ResponseInterceptor;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class FeignResponseInterceptor implements ResponseInterceptor {

    @PostConstruct
    public void init() {
        log.info("FeignResponseInterceptor initialized");
    }

    @Override
    public Object intercept(InvocationContext invocationContext, Chain chain) throws Exception {
        // todo try catch
        Object res = chain.next(invocationContext);
        BasinLogVO basinLogVO = BasinLogContext.get();
        List<BasinLogVO> traces = basinLogVO.getTraces();
        int pos = traces.size() - 1;
        traces.get(pos).setResult(res);
        long endTime = System.currentTimeMillis();
        traces.get(pos).setEndTime(endTime);
        traces.get(pos).setCostTime(endTime - traces.get(pos).getStartTime());
        log.info("response: {}", res);
        return res;
    }
}

